﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using WisPortal.Models;
using System.IO;
using System.Xml;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using WisPortal.Data;
using WisPortal;

namespace WisPortal.Areas.Train.Controllers
{
    /// <summary>
    /// 提供文件处理相关的接口
    /// </summary>
    public class FileController : BaseController
    {
        private const string CATEGORY_NODE = "Category";
        private const string CATEGORIES_NODE = "Categories";
        
        [AllowAnonymous]
        public ActionResult GetSharedFiles()
        {
            StringBuilder sql = new StringBuilder();
            sql.Append("SELECT   TSX_FILE_CATEGORY.ID,TSX_FILE_CATEGORY.MODIFIEDTIME, TSX_FILE_CATEGORY.NAME AS CATEGORYNAME, TSX_FILE_CATEGORY.DESCRIPTION,");
            sql.Append("TSX_FILE_CATEGORY.POSITION, TSX_FILE_CATEGORY.PARENT_ID, TSX_FILE_FILES.ID AS FILEID, ");
            sql.Append("TSX_FILE_FILES.CREATETIME, TSX_FILE_FILES.FILENAME, TSX_FILE_FILES.SIZE, TSX_FILE_FILES.SAVEPATH,");
            sql.Append("TSX_FILE_FILES.CONTENTTYPE, TSX_FILE_FILES.DESCRIPTION AS FILE_DESCRIPTION, TSX_FILE_FILES.STATUS, ");
            sql.Append("TSX_FILE_FILES.MODIFIEDTIME ");
            sql.Append("FROM      TSX_FILE_CATEGORY LEFT OUTER JOIN ");
            sql.Append("TSX_FILE_FILES ON TSX_FILE_CATEGORY.ID = TSX_FILE_FILES.CATEGORY_ID ");
            sql.Append("WHERE	TSX_FILE_FILES.STATUS = 0 OR TSX_FILE_FILES.STATUS IS NULL ");
            sql.Append("ORDER BY	TSX_FILE_CATEGORY.ID,TSX_FILE_CATEGORY.POSITION");

            DataSet ds = DB.GetDataSet(sql.ToString());

            if (DB.HasData(ds))
            {
                XmlDocument doc = new XmlDocument();

                XmlNode rootCategoriesNode = doc.CreateElement(CATEGORIES_NODE);
                doc.AppendChild(rootCategoriesNode);
                DataMapping dm = new DataMapping(HttpContext);
                foreach (DataRow row in ds.Tables[0].Rows)                
                {
                    XmlNode categoryNode = GetCategoryNode(doc, dm, ds.Tables[0], row, rootCategoriesNode);
                    if (row["FILEID"] != DBNull.Value)
                    {
                        //File Node
                        XmlNode fileNode = CreateFileNodeByDataRow(doc, dm, row);
                        if (categoryNode.SelectSingleNode("Files") == null)
                        {
                            categoryNode.AppendChild(doc.CreateElement("Files"));
                        }
                        categoryNode.SelectSingleNode("Files").AppendChild(fileNode);
                    }
                    //else
                        //Do nothing;                       
                }
                return Content(JsonConvert.SerializeXmlNode(doc, Newtonsoft.Json.Formatting.Indented).Replace("\"@","\""));
            }
            else
                return GetResult(CODE_ERROR_NODATAFOUND, "未找到文件共享数据");
        }



        /// <summary>
        /// Get or create a cagtegory node
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="dm"></param>
        /// <param name="row"></param>
        /// <returns></returns>
        protected XmlNode GetCategoryNode(XmlDocument doc, DataMapping dm,DataTable table, DataRow row, XmlNode rootCategoriesNode)
        {
            XmlNode categoryNode = doc.SelectSingleNode(string.Format(".//Category[@id='{0}']", row["ID"].ToString()));
            if (categoryNode == null)
            {
                //New Category                        
                XmlNode newCategoryNode = CreateCategoryNodeByDataRow(doc,dm,row);
                if (row["PARENT_ID"] == DBNull.Value)
                {
                    rootCategoriesNode.AppendChild(newCategoryNode);
                }
                else
                {
                    //寻找要添加的Categories节点，如未发现父节点则添加到跟节点中
                    XmlNode parentCategoryNode = doc.SelectSingleNode(string.Format(".//Category[@id='{0}']", row["PARENT_ID"].ToString()));
                    if (parentCategoryNode == null)
                    {
                        DataRow[] parentRows = table.Select(string.Format("ID = '{0}'",row["PARENT_ID"]));
                        if (parentRows != null && parentRows.Length > 0)
                        {
                            //递归调用，找到父Category节点
                            parentCategoryNode = GetCategoryNode(doc, dm, table, parentRows[0], rootCategoriesNode);                            
                        }
                        else
                        {
                            parentCategoryNode = rootCategoriesNode.ParentNode;
                        }
                    }
                    
                    if (parentCategoryNode.SelectSingleNode(CATEGORIES_NODE) == null)
                    {
                        parentCategoryNode.AppendChild(doc.CreateElement(CATEGORIES_NODE));
                    }
                    //Add to parent
                    parentCategoryNode.SelectSingleNode(CATEGORIES_NODE).AppendChild(newCategoryNode);
                    
                }
                categoryNode = newCategoryNode;
            }
            
            return categoryNode;
        }

        protected XmlNode CreateCategoryNodeByDataRow(XmlDocument doc,DataMapping dm, DataRow row)
        {
            XmlNode node = doc.CreateElement(CATEGORY_NODE);

            dm.AddAttributeToNode(doc,node,"id",row["ID"].ToString());
            dm.AddAttributeToNode(doc, node, "name", row["CATEGORYNAME"].ToString());
            dm.AddAttributeToNode(doc, node, "description", row["DESCRIPTION"].ToString());
            dm.AddAttributeToNode(doc, node, "parent_id", row["PARENT_ID"].ToString());
            dm.AddAttributeToNode(doc, node, "position", row["POSITION"].ToString());
            dm.AddAttributeToNode(doc, node, "modifiedtime", row["MODIFIEDTIME"].ToString());
            return node;
        }

        protected XmlNode CreateFileNodeByDataRow(XmlDocument doc, DataMapping dm, DataRow row)
        {
            XmlNode node = doc.CreateElement("File");

            dm.AddAttributeToNode(doc, node, "id", row["FILEID"].ToString());
            dm.AddAttributeToNode(doc, node, "filename", row["FILENAME"].ToString());
            dm.AddAttributeToNode(doc, node, "description", row["FILE_DESCRIPTION"].ToString());
            dm.AddAttributeToNode(doc, node, "size", row["SIZE"].ToString());
            dm.AddAttributeToNode(doc, node, "createtime", row["CREATETIME"].ToString());
            dm.AddAttributeToNode(doc, node, "modifiedtime", row["MODIFIEDTIME"].ToString());

            string url = string.Format("{0}Train/File/Download?file={1}&name={2}",
                Request.ApplicationPath,
                row["SAVEPATH"].ToString(),
                row["FILENAME"].ToString());
            dm.AddAttributeToNode(doc, node, "url", url);
            dm.AddAttributeToNode(doc, node, "contenttype", row["CONTENTTYPE"].ToString());
            dm.AddAttributeToNode(doc, node, "savepath", row["SAVEPATH"].ToString());
            return node;
        }

        public ActionResult Download(string file,string name)
        {
            file = string.Format("{0}{1}", Server.MapPath("~/UploadFile/Train"), file);
            if (System.IO.File.Exists(file))
                return File(file, "application/octet-stream",name);
            else
                return GetResult(CODE_ERROR_NODATAFOUND, "未找到文件");
        }

        /// <summary>
        /// Upload user file
        /// </summary>
        /// <param name="deviceId"></param>
        /// <param name="dataid"></param>
        /// <param name="createdtime"></param>
        /// <param name="userid"></param>
        /// <returns></returns>
        public ActionResult Upload(string deviceId, string dataId,string categoryId, string userid)
        {
            if(Request.Files.Count > 0)
            {
                for (int i = 0; i < Request.Files.Count;i++ )
                {
                    string sql = string.Format("INSERT INTO SYS_Feedbacks ([Description],[CreatedTime],[IP],[UserID],[DeviceID]) VALUES (@Description,@CreatedTime,@IP,@UserID,@DeviceID)");
            
                    //List<SqlParameter> parameters = new List<SqlParameter>();
                    //parameters.Add(new SqlParameter("Description", title));
                    //parameters.Add(new SqlParameter("CreatedTime", DateTime.Now.ToString()));
                    //parameters.Add(new SqlParameter("IP", ip));
                    //parameters.Add(new SqlParameter("UserID", userid));
                    //parameters.Add(new SqlParameter("DeviceID", deviceid));

                    //DB.ExecuteNonQuery(DB.ConnectionStringFoundation, System.Data.CommandType.Text, sql, parameters.ToArray());

                    string fileName = System.IO.Path.GetFileName(Request.Files[i].FileName);
                    string filePath = Server.MapPath(string.Format("~/UploadFile/Train/FileShare/DeviceFile/{0}/{1}-{2}-{3}-{4}",
                        deviceId, 
                        userid, 
                        dataId, 
                        categoryId, 
                        fileName));
                    if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(filePath)))
                    {
                        System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(filePath));
                    }

                    Request.Files[i].SaveAs(filePath);
                }            
                return GetResult(CODE_SUCCESS,"上传文件成功");
            }
            else
                return GetResult(CODE_ERROR_NODATAFOUND,"未发现上传的文件");
        }

        /// <summary>
        /// Upload IM File
        /// </summary>
        /// <param name="dataId"></param>
        /// <returns></returns>
        public ActionResult UploadIMFile(string dataId)
        {
            if (Request.Files.Count > 0)
            {
                string filePath = Server.MapPath(string.Format("~/UploadFile/Train/FileShare/IMFile/{0}",dataId));
                if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(filePath)))
                {
                    System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(filePath));
                }

                Request.Files[0].SaveAs(filePath);
                return GetResult(CODE_SUCCESS, "上传文件成功");
            }
            else
                return GetResult(CODE_ERROR_NODATAFOUND, "未发现上传的文件");
        }

        /// <summary>
        /// Download IM File
        /// </summary>
        /// <param name="dataId"></param>
        /// <returns></returns>
        public ActionResult DownloadIMFile(string dataId)
        {
            string filePath = Server.MapPath(string.Format("~/UploadFile/Train/FileShare/IMFile/{0}", dataId));                
            if (System.IO.File.Exists(filePath))
            {
                return File(filePath, "application/octet-stream");
            }
            else
                return GetResult(CODE_ERROR_NODATAFOUND, "未发现要下载的文件");
        }
    }
}
